import os


class BaseLogger:
    def __init__(self, save_dir, exp_name, mode):
        self.save_dir = save_dir
        self.exp_name = exp_name
        self.mode = mode
        if not os.path.exists(os.path.join(self.save_dir, self.exp_name)):
            os.makedirs(os.path.join(self.save_dir, self.exp_name), 0o0777)

    def log(self, log_content):
        log_str = ''
        if isinstance(log_content, str):
            log_str = log_content
        elif isinstance(log_content, dict):
            for key, value in log_content.items():
                log_str += '{}:{}  |  '.format(str(key), str(value))
        elif isinstance(log_content, list):
            log_str = self.print_dict(log_content[0], 0)

        with open(os.path.join(self.save_dir, self.exp_name, self.mode + '_log.txt'), 'a') as f:
            f.write(log_str + '\n')
        print(log_str)

    def print_dict(self, d, indent):
        log_str = ''
        for k, v in d.items():
            if isinstance(v, dict):
                log_str += '{}{}:\n'.format('\t' * indent, k)
                log_str += self.print_dict(v, indent + 1)
            else:
                log_str += '{}{} : {}\n'.format('\t' * indent, k, str(v))
        return log_str
